// pages/addMemo/index.js
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
const utils = require("../../utils/util");
const db = wx.cloud.database();
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 优先级选择项目
    levelColumns: ['无', '低', '中', '高'],
    memoId: '',
    title: '',
    content: '',
    levelNum: 0,
    levelName: '无',
    levelShow: false,
    levelDirection: '', //箭头展示位置
    status: 0,
    statusChecked: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      memoId: options.memoId
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var memoId = that.data.memoId;
    //获取备忘信息
    getMemo(that, memoId);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // 设置分享标题
    return {
      title: app.globalData.shareTitle,
      path: '/pages/index/index'
    }
  },

  /**
   * 标题输入监听
   */
  onChangeTitle: function ({
    detail
  }) {
    var that = this;
    that.setData({
      title: detail
    })
  },


  /**
   * 点击选择优先级
   */
  onClickLevel: function () {
    var that = this;
    that.setData({
      levelShow: true,
      levelDirection: 'down'
    })
  },

  /**
   * 关闭弹框监听事件
   */
  onCloseLevel: function () {
    var that = this;
    that.setData({
      levelShow: false,
      levelDirection: ''
    })
  },

  /**
   * 选择事件
   */
  onConfirmLevel: function ({
    detail
  }) {
    var that = this;
    var index = detail.index;
    var value = detail.value;
    that.setData({
      levelNum: index,
      levelName: value,
      levelShow: false,
      levelDirection: ''
    })
  },

  /**
   * 内容输入监听
   */
  onChangeContent: function ({
    detail
  }) {
    var that = this;
    that.setData({
      content: detail
    })
  },

  /**
   * 是否完成选择监听
   */
  onChangeStatus: function ({
    detail
  }) {
    var that = this;
    if (detail) {
      that.setData({
        status: 1,
        statusChecked: detail
      })
    } else {
      that.setData({
        status: 0,
        statusChecked: detail
      })
    }

  },
  /**
   * 点击更新
   */
  onUpdateSubmit: function () {
    var that = this;
    var memoId = that.data.memoId;
    var title = that.data.title;
    var content = that.data.content;
    var level = that.data.levelNum;
    var status = that.data.status;

    //表单验证
    if (test(title, content)) {
      //内容验证并更新
      contentCheck(memoId, title, content, level, status);
    }
  }
})


/**
 * 表单验证
 * @param {*} title 
 * @param {*} content 
 */
function test(title, content) {
  if (!title) {
    Toast('请输入标题')
    return false;
  } else if (!content) {
    Toast('请输入内容')
    return false;
  } else {
    return true;
  }
}


/**
 * 通过备忘Id获取备忘记录
 * @param {备忘Id}} memoId 
 */
function getMemo(that, memoId) {
  db.collection(app.globalData.memoCollection)
    .doc(memoId)
    .get().then(res => {
      var data = res.data;
      var levelNum = data.level;
      that.setData({
        title: data.title,
        content: data.content,
        level: data.level,
        levelNum: levelNum,
        levelName: levelNum == 1 ? '低' : levelNum == 2 ? '中' : levelNum == 3 ? '高' : '无',
        status: data.status,
        statusChecked: data.status === 1 ? true : false
      })
    })
    .catch(error => {
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    })
}

/**
 * 更新
 * @param {*} title 
 * @param {*} content 
 * @param {*} level 
 * @param {*} status 
 */
function update(memoId, title, content, level, status) {
  db.collection(app.globalData.memoCollection).doc(memoId).update({
    data: {
      "title": title,
      "content": content,
      "level": level,
      "status": status,
      "create_time": utils.getDateTime(new Date())
    }
  }).then(res => {
    var errMsg = res.errMsg;
    if (errMsg.indexOf('update:ok') != -1) {
      Dialog.confirm({
        title: '更新成功',
        message: '您已更新成功！您可以选择【继续更新】或者【返回】到上一页',
        confirmButtonText: '继续更新',
        cancelButtonText: '返回'
      })
        .then(() => { })
        .catch(() => {
          //返回上一页
          wx.navigateBack({});
        });
    }
  })
    .catch(error => {
      Toast.loading({
        type: 'text',
        duration: 1500,
        message: error.errMsg
      });
    })
}

/**
 * 内容检测
 * @param {} text 
 */
function contentCheck(memoId, title, content, level, status) {
  wx.cloud.callFunction({
    name: 'ContentCheck',
    data: {
      txt: title + content
    },
    success(res) {
      if (res.result.errCode == 87014) {
        Toast.loading({
          type: 'text',
          duration: 1500,
          message: "存在文字违规，请修改后再保存"
        });
        return false;
      } else {
        //更新
        update(memoId, title, content, level, status);
      }
    }, fail(err) {
      console.log('ContentCheck-err', err)
      return false;
    }
  })
}